<?php

class ApiController extends Controller {
    public function init() {        
        parent::init();
        Yii::app()->errorHandler->errorAction='api/error';
    }
    public function filters() {
        return array(
            'verifyLoggedIn - login,signature,updateDispatchTech,test,updatePart,testInventory,
                                technoteDownload,technoteUpdate,technoteCreate,technoteDelete,actionCustnoteDownloadDownload'
        );
    }
    public function actionError(){
        echo json_encode(array(
            'Status'=>500,
            'Message'=>'Unknown error'
        ));
    }
    public function filterVerifyLoggedIn($filterChains) {
        if (isset($_GET['username']) && isset($_GET['password']) && isset($_GET['sessionid'])) {
            $username = $_GET['username'];
            $password = $_GET['password'];
            $sessionid = $_GET['sessionid'];

            $user = NULL;
            
            $user = Yii::app()->db->createCommand('select * from tbl_users where email=:email AND password=:password AND sessionid=:sessionid')
                            ->bindValues(array(
                                'email' => $username,
                                'password' => md5($password),
                                'sessionid' => $sessionid
                            ))->queryRow();
            
            if ($user == NULL) {
                $this->_sendResponse(401, 'Authentication Failed', true);
            }
        } else {
            $this->_sendResponse(400, 'Check your login parameters', true);
        }
        $filterChains->run();
    }

    public function actionLogout() {
        //clear session id of user
        $row=Yii::app()->db->createCommand()->update('tbl_users', array(
            'sessionid'=>NULL
        ), 'email=:email',array(
            'email'=>$_GET['username']
        ));
        if($row>0){
            $this->_sendResponse(200, CJSON::encode(array(
                    'Status' => 200,
                    'Message' => 'Logout Successful'
                )));
        }else{
            echo json_encode(array(
                'Status'=>401,
                'Message'=>'Can not log out'
            ));
        }
        
    }

    public function actionLogin() {
        //check for required parameter before proceed
        if (!isset($_GET['username']) || !isset($_GET['password']) || !isset($_GET['deviceid'])) {
            $this->_sendResponse(400);
        }

        $username = $_GET['username'];
        $password = $_GET['password'];
        $deviceid = $_GET['deviceid'];
        //get all user who have mobile permission
        $users = getUserByPermission(Users::PRIVILEGE_MOBILE_LOGIN);
        if (in_array($username, $users)) {
            
            //$login->rememberMe = 0;
            //check login
                
                $user = Users::model()->find('email=:email AND password=:password ', array(
                    'email' => $username,
                    'password'=>md5($password))
                        );
                if($user==NULL){
                    echo json_encode(array(
                        'Status'=>401,
                        'Message'=>'Email or password is wrong'
                    ));
                    return;
                }
                //login ok continue
                $sessionid = createRandomString(30);
                //upload login info
                $user->updateAll(array(
                    'deviceid' => $deviceid,
                    'mobileloggedin' => 1,
                    'sessionid' => $sessionid
                        ), 'email=:email', array('email' => $username));

                $rs = NULL;
                //return data base on user type: customer or employee
                if ($user->employeeid != NULL && $user->custno == NULL) {
                    $employee = Employees::model()->findByPk($user->employeeid);
                    $rs = array(
                        'Status' => 200,
                        'UserType' => 'Employee',
                        'WareHouse' => $employee->getAssignedWareHouse(),
                        'EmpNo' => $employee->empno,
                        'Name' => $employee->firstname . ' ' . $employee->lastname,
                        'SessionId' => $sessionid,
                            //'imagelink' => Yii::app()->request->getHostInfo() . '/images/content/' . $employee->image,
                    );
                } else if ($user->custno != NULL) {
                    $customer = Customers::model()->findByPk($user->custno);
                    $rs = array(
                        'Status' => 200,
                        'UserType' => 'Customer',
                        'CustNo' => $customer->custno,
                        'Name' => $customer->firstname . ' ' . $customer->lastname,
                        'SessionId' => $sessionid,
                            //'image' => Yii::app()->request->getHostInfo() . '/images/content/' . $customer->image,
                    );
                }
                $this->_sendResponse(200, CJSON::encode($rs));
           
        } else {
            $this->_sendResponse(401);
        }
    }

    private function _sendResponse($status = 200, $body = '', $error=false, $content_type = 'text/html') {
        // set the status
        $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
        header($status_header);
        // and the content type
        header('Content-type: ' . $content_type);

        // pages with body are easy
        if ($body != '') {
            // send the body
            if ($error === false) {
                echo $body;
            } else {
                echo json_encode(array(
                    'Status' => $status,
                    'Reason' => $body
                ));
            }
            Yii::app()->end();
        }
        // we need to create the body if none is passed
        else {
            // create some body messages
            $message = '';

            // this is purely optional, but makes the pages a little nicer to read
            // for your users.  Since you won't likely send a lot of different status codes,
            // this also shouldn't be too ponderous to maintain
            switch ($status) {
                case 401:
                    $message = 'You must be authorized to view this page.';
                    break;
                case 404:
                    $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
                    break;
                case 500:
                    $message = 'The server encountered an error processing your request.';
                    break;
                case 501:
                    $message = 'The requested method is not implemented.';
                    break;
                default:
                    $message = $this->_getStatusCodeMessage($status);
            }
            echo json_encode(array(
                'Status' => $status,
                'Reason' => $message
            ));
//
//            // servers don't always have a signature turned on 
//            // (this is an apache directive "ServerSignature On")
//            $signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];
//
//            // this should be templated in a real-world solution
//            $body = '
//            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
//            <html>
//            <head>
//                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
//                <title>' . $status . ' ' . $this->_getStatusCodeMessage($status) . '</title>
//            </head>
//            <body>
//                <h1>' . $this->_getStatusCodeMessage($status) . '</h1>
//                <p>' . $message . '</p>
//                <hr />
//                <address>' . $signature . '</address>
//            </body>
//            </html>';


            exit;
        }
    }

    private function _getStatusCodeMessage($status) {
        // these could be stored in a .ini file and loaded
        // via parse_ini_file()... however, this will suffice
        // for an example
        $codes = Array(
            200 => 'OK',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
        );
        return (isset($codes[$status])) ? $codes[$status] : '';
    }

    private function _checkAuth() {
        // Check if we have the USERNAME and PASSWORD HTTP headers set?
        if (!(isset($_SERVER['HTTP_X_USERNAME']) and isset($_SERVER['HTTP_X_PASSWORD']))) {
            // Error: Unauthorized
            $this->_sendResponse(401);
        }
        $username = $_SERVER['HTTP_X_USERNAME'];
        $password = $_SERVER['HTTP_X_PASSWORD'];
        // Find the user
        $user = Users::model()->find('LOWER(email)=:email', array('email' => strtolower($username)));
        if ($user === null) {
            // Error: Unauthorized
            $this->_sendResponse(401, 'Error: User Name is invalid');
        } else if (!$user->password != md5($password)) {
            // Error: Unauthorized
            $this->_sendResponse(401, 'Error: User Password is invalid');
        }
    }

    public function actionDispatchList() {
//        $user = Users::model()->find('LOWER(email)=:email', array('email' => strtolower(Yii::app()->user->name)));
//        if ($user->employeeid != NULL) {
//            $empno = $user->employeeid;
//        } else {
//            $this->_sendResponse(400, 'Logged user is not an employee', true);
//        }
        $user = Users::model()->find('LOWER(email)=:email', array(
            'email' => strtolower($_GET['username'])
            ));
      
        $empno=$user->employeeid;
        $dispatchList = Yii::app()->db->createCommand('select dispatch from tbl_dispatch_tech where empno=:empno')
                        ->bindValue('empno', $user->employeeid)->queryAll();
        $rs = array();
        $rs['Status'] = 200;
        foreach ($dispatchList as $i => $item) {
            $dispatch = Dispatchdetails::model()->findByPk($item['dispatch']);
            if ($dispatch == NULL)
                continue;
            $location = $dispatch->location;
            $rs['data'][$i]['dispatch'] = $dispatch->dispatch;
            if ($location != NULL) {
                $rs['data'][$i]['locname'] = $location->locname;
                $rs['data'][$i]['add1'] = $location->add1;
                $rs['data'][$i]['city'] = $location->city;
                $rs['data'][$i]['state'] = $location->state;
                $rs['data'][$i]['zip'] = $location->zip;
                $rs['data'][$i]['contacts'] = $location->getLocationcontacts();
                $rs['data'][$i]['locationnotes'] = $location->notes;
                $rs['data'][$i]['custno'] = $location->custno;
                $rs['data'][$i]['locno'] = $location->locno;
            }

            $rs['data'][$i]['calledinby'] = $dispatch->calledinby;
            $rs['data'][$i]['serviceagrno'] = $dispatch->serviceagrno;
            $rs['data'][$i]['dispatchnotes'] = $dispatch->notes;
            $rs['data'][$i]['pastcustomernotes'] = Notes::getLastCustomerNotes($dispatch->dispatch,$dispatch->custno);
            $rs['data'][$i]['pasttechnotes'] = Notes::getLastTechNotes($dispatch->dispatch,$empno);
            if ($dispatch->lastestTech != NULL) {
                $rs['data'][$i]['status'] = $dispatch->lastestTech->status;
            }
            $rs['data'][$i]['locationimage'] = Yii::app()->baseUrl . '/' . getImage($location->image, 'images/content', 100, 100);
            //$rs[$i]['pmstatus']
            //print_r($dispatch->equipments);
            $dpEquipList = Dispatchequipment::model()->findAll('dispatch=:dispatch', array('dispatch' => $dispatch->dispatch));

            $pm = false;
            foreach ($dpEquipList as $dpEquip) {
                $equip = $dpEquip->equipment;
                if ($equip != NULL) {
                    if ($equip->pmrequired == Equipment::PM_YES) {
                        $pm = true;
                        break;
                    }
                }
            }

            if ($pm) {
                $rs['data'][$i]['pmstatus'] = 'Yes';
            } else {
                $rs['data'][$i]['pmstatus'] = 'No';
            }
        }

        $this->_sendResponse(200, CJSON::encode($rs));
    }

    public function actionPictureUpload() {
        if (isset($_GET['LocNo']) && isset($_GET['CustNo'])) {
            $locno = $_GET['LocNo'];
            $custno = $_GET['CustNo'];
            if (isset($_FILES['file'])) {  // file was send from browser

                if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {  // no error
                    $filename = $_FILES['file']['name']; // file name 
                    $name = getFileBodyName($filename);
                    $ext = getFileExt($filename);
                    $newname = $name . time() . $ext;
                    $upload_result = move_uploaded_file($_FILES['file']['tmp_name'], 'images/content/' . $newname);
                    if ($upload_result) {
                        Yii::app()->db->createCommand()->update('tbl_locations', array(
                            'image' => $newname
                                ), array(
                            'locno' => $locno,
                            'custno' => $custno
                        ));
                        $this->_sendResponse(200, json_encode(array(
                                    'Status' => 200,
                                    'URL' => Yii::app()->baseUrl . getImage($newname, '/images/content/', 100, 100)
                                )));
                    }
                } elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
                    $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                else
                    $result_msg = 'Unknown error';

                $this->_sendResponse(500, $result_msg, true);
            }else {
                $this->_sendResponse(400, 'Upload file cannot find', true);
            }
        } else if ($isset($_GET['CustNo'])) {
            $custno = $_GET['CustNo'];
            if (isset($_FILES['file'])) {  // file was send from browser

                if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {  // no error
                    $filename = $_FILES['file']['name']; // file name 
                    $name = getFileBodyName($filename);
                    $ext = getFileExt($filename);
                    $newname = $name . time() . $ext;
                    $upload_result = move_uploaded_file($_FILES['file']['tmp_name'], 'images/content/' . $newname);
                    if ($upload_result) {
                        Yii::app()->db->createCommand()->update('tbl_customers', array(
                            'image' => $newname
                                ), array(
                            'custno' => $custno
                        ));
                        $this->_sendResponse(200, json_encode(array(
                                    'Status' => 200,
                                    'URL' => Yii::app()->baseUrl . getImage($newname, '/images/content/', 100, 100)
                                )));
                    }
                } elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
                    $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                else
                    $result_msg = 'Unknown error';

                $this->_sendResponse(500, $result_msg, true);
            }else {
                $this->_sendResponse(400, 'Upload file cannot find', true);
            }
        } else {
            //custno and locno count be find
            $this->_sendResponse(400, 'Invalid upload parameters');
        }
    }

    public function actionAddNotes($dispatch, $date, $notes, $user=NULL, $empno=NULL) {
        $model = new Notes();
        $model->dispatch = $dispatch;
        $model->dateofnote = $date;
        $model->note = $notes;
        $model->custno = $user;
        $model->empno = $empno;
        if ($model->save()) {
            $this->_sendResponse(200, json_encode(array(
                        'Status' => 200,
                        'Message' => 'Save note successful'
                    )));
        } else {
            $error['Errors'] = $model->getErrors();
            $error['Status'] = 500;
            echo json_encode($error);
        }
    }

    public function actionChangeStatus($dispatch, $empno, $newstatus) {
        $model = Dispatchtech::model()->find('dispatch=:dispatch AND empno=:empno',array(
            'dispatch'=>$dispatch,
            'empno'=>$empno
        ));
        
        /* @var $model Dispatchtech */
        if($model!=NULL){
           $rs = $model->changeStatus($newstatus);
            if ($rs) {
                echo json_encode(array(
                    'Status' => 200,
                    'Message' => 'Change status successful'
                ));
            } else {
                echo json_encode(array(
                    'Status' => 500,
                    'Errors' => $model->getErrors()
                ));
            } 
        }
        //model can't find, error
        
        echo json_encode(array(
            'Status'=>500,
            'Message'=>'Can not find the object'
        ));
    }

    public function actionListEquipment($custno, $locno) {
        $equiplist = Equipment::model()->findAll('custno=:custno AND locno=:locno', array(
            'custno' => $custno,
            'locno' => $locno
                ));
        $rs = array();
        foreach ($equiplist as $i=>$item) {
            /* @var $item Equipment */
            $rs[] = $item->attributes;
            $rs[$i]['pmrequiredText'] = $item->pmrequiredText;
            $rs[$i]['statusText'] = $item->statusText;
            $rs[$i]['planTypeText'] = $item->PlanTypeText;
        }
        echo json_encode(array(
            'Status' => 200,
            'Data' => $rs
        ));
    }
    public function actionProvision(){
        $codeList=Statuscode::model()->findAll();
        $rs=array();
        foreach($codeList as $i=>$item){
            /* @var $item Statuscode */
            $rs[]=$item->getAttributes();
            $rs[$i]['icon']=Yii::app()->request->getBaseUrl(true).'/'.getImage($item->icon, 'images', 32, 32);
        }
        echo json_encode(array(
            'Status'=>200,
            'Data'=>$rs
        ));
    }
    public function actionAddEquipment() {
        if(!isset($_GET['Equipment'])){
            $this->_sendResponse(401,'Invalid parameters',true);
        }
        $model=new Equipment;
        $model->attributes=$_GET['Equipment'];        
        $newname = '';
        if (isset($_FILES['image'])) {  // file was send from browser

            if ($_FILES['image']['error'] == UPLOAD_ERR_OK) {  // no error
                $filename = $_FILES['image']['name']; // file name 
                $name = getFileBodyName($filename);
                $ext = getFileExt($filename);
                $newname = $name . time() . $ext;
                
                
            } elseif ($_FILES['image']['error'] == UPLOAD_ERR_INI_SIZE)
                $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
            else
                $result_msg = 'Unknown error';
        }
        $model->image=$newname;
        if($model->save()){
            //move our image
            if($newname!=''){
                $upload_result = move_uploaded_file($_FILES['image']['tmp_name'], 'images/content/' . $newname);
            }
            
            echo json_encode(array(
                'Status'=>200,
                'Message'=>'Add Equipment Successful'
            ));
        }else{
            echo json_encode(array(
                'Status'=>400,
                'Errors'=>$model->getErrors()
            ));
        }
        
        
        
    }
    public function actionPartList(){
        $list=Yii::app()->db->createCommand('select partno,type,cat,subcat,description,imagepath from tbl_inventory where type="I"')->queryAll();
        $length=count($list);
        for($i=0;$i<$length;$i++){
            $list[$i]['imagepath']=Yii::app()->request->getHostInfo('https') . '/' . getImage($list[$i]['imagepath'], 'images/content/inventory', 100, 100);
        }
        echo json_encode($list);
    }

    public function actionSignature(){
        $this->logPost();
        $signature = new DispatchSignatures();
        $signature->attributes = $_POST;
   
        $ext = substr($_FILES['filename']['name'],strlen($_FILES['filename']['name'])-3);
        $filename = 'images/content/signature/'.$_FILES['filename']['name'];
        move_uploaded_file($_FILES['filename']['tmp_name'], $filename);
        $signature->filename = $filename;
        $signature->save();
        
        
    }
    public function actionUpdateDispatchTech(){
        $this->logPost();
        $model =  Dispatchdetails::model()->findByPk($_POST['dispatch']);        
        //$oldStatus = $model->status;                   
        $empno =$_REQUEST['empno'];
        $newstatus = $_REQUEST['newstatus'];
        if($newstatus == "Reassign"){
            $empno = '0001';
        }
        $time = DateUtil::convertDate('H:i:s',$_POST['time']);
        if ($model!=null) {
            $model->lastestTech->changeStatus($newstatus,$empno,$_POST['date'],$time,true);           
        }               
    }

    public function actionUpdatePart(){
        $this->logPost();
        $dispatch = $_POST['dispatch'];
        $num = Yii::app()->db->createCommand('select max(counter) from tbl_dispatchparts where dispatch=:dispatch')
                                        ->bindValues(array(
                                            'dispatch'=>$dispatch
                                        ))->queryScalar();
        $counter = str_pad($num + 1, 3, '0', STR_PAD_LEFT);
        $model = new Dispatchparts();
        $model->dispatch = $dispatch;
        $model->quanity = $_POST['quanity'];
        $model->noprint = 0;
        $model->added_by = $_POST['empno'];
        $model->counter = $counter;
        $time = DateUtil::convertDate('H:i:s',$_POST['time']);        
        $model->added_date = $_POST['date'].' '.$time;
        $model->price = 0;
        $model->partno = $_POST['partno'];
        $inv = Inventory::model()->findByPk($_POST['partno']);
        if($inv!=null){
            $model->partdesc = $inv->description;
        }
        $warehouse = Warehouse::model()->find('empno=:empno',array('empno'=>$_POST['empno']));
        if($warehouse !=null){
            $model->warehouse = $warehouse->warehouseid;
        }

        $model->save();
        
    }

    public function actionTestInventory(){
        $inventory = Inventory::model()->findByPk('C-Software Maint.');
        var_dump($inventory->isTaxable('0000188'));
        $ledger = new ContractLedger();
        $ledger->partno = 'C-Software Maint.';
        $ledger->autoSetTaxed('0000188');
        echo $ledger->taxed;
    }

    public function actionTechnoteDownload(){
        $this->logPost();
        if(isset($_REQUEST['dispatch']) && isset($_REQUEST['empno'])){
            $dispatch = $_REQUEST['dispatch'];
            $empno = $_REQUEST['empno'];
            $crit = new CDbCriteria();
            $crit->compare('dispatch',$dispatch);    
            $crit->compare('empno',$empno);
            $notes = Notes::model()->findAll($crit);
            $items = array();
            foreach($notes as $note){
                $items[] = $note->attributes;
            }

            $this->apiOutput(true,$items);
        }else{
            $this->apiOutput(false);
        }
        
    }

    public function apiOutput($success,$items = null){
        $status = $success?'Complete':'Error';
        $response['apiOutput']['status'] = $status;
        if($items!=null){
            $response['apiOutput']['items'] = $items;            
        }
        echo json_encode($response);
        Yii::app()->end();
    }
    public function actionTechnoteUpdate(){
        $this->logPost();
        $noteid = Yii::app()->request->getPost('noteid');
        $time = DateUtil::convertDate('H:i:s',Yii::app()->request->getPost('time'));
        if($noteid!=null){
            $note = Notes::model()->findByPk($noteid);
            
            if($note!=null){
                $note->attributes = $_POST;
                $note->time = $time;
                if($note->save()){
                    $this->apiOutput(true);
                }else{
                    $this->apiOutput(false,$note->errors);
                }     
            }   
        }else{

        }
    }

    public function actionTechnoteDelete(){
        $this->logPost();
        $noteid = Yii::app()->request->getPost('noteid');
        $time = DateUtil::convertDate('H:i:s',Yii::app()->request->getPost('time'));
        if($noteid!=null){
            $note = Notes::model()->findByPk($noteid);
            $content = Yii::app()->request->getPost('note');
            if($note!=null && $content == 'deletedByTech'){
                $note->delete();
                $this->apiOutput(true);
            }   
        }
        $this->apiOutput(false);
    }

    public function actionTechnoteCreate(){
        $this->logPost();
        $time = DateUtil::convertDate('H:i:s',Yii::app()->request->getPost('time'));
        $note = new Notes();
        $note->attributes = $_POST;
        $note->time = $time;
        if($note->save()){
            $this->apiOutput(true);
        }else{
            $this->apiOutput(false,$note->errors);
        }
    }

    public function actionCustnoteDownload(){
        $this->logPost();
        if(isset($_REQUEST['dispatch']) && isset($_REQUEST['custno'])){
            $dispatch = $_REQUEST['dispatch'];
            $empno = $_REQUEST['custno'];
            $crit = new CDbCriteria();
            $crit->compare('dispatch',$dispatch);    
            $crit->compare('custno',$empno);
            $notes = Notes::model()->findAll($crit);
            $items = array();
            foreach($notes as $note){
                $items[] = $note->attributes;
            }
            $this->apiOutput(true,$items);
        }else{
            $this->apiOutput(false);
        }
    }

    protected function logPost(){
        $output = Yii::app()->controller->action->id.' '.serialize($_POST).PHP_EOL.PHP_EOL;
        $f = fopen('apiLog','a+');
        fwrite($f,$output);
        fclose($f);
    }
    

}

?>
